package com.tianji.learning.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.*;
import com.tianji.learning.domain.dto.LearningPlanDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.domain.vo.LearningLessonVO;
import com.tianji.learning.domain.vo.LearningPlanPageVO;
import com.tianji.learning.domain.vo.LearningPlanVO;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.PlanStatus;
import com.tianji.learning.mapper.LearningLessonMapper;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.service.ILearningRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

import static com.tianji.learning.enums.LessonStatus.LEARNING;
import static com.tianji.learning.enums.LessonStatus.NOT_BEGIN;

/**
 * <p>
 * 学生课程表 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2025-10-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LearningLessonServiceImpl extends ServiceImpl<LearningLessonMapper, LearningLesson> implements ILearningLessonService {
    private final CourseClient courseClient;
    private final CatalogueClient catalogueClient;
    private final LearningRecordMapper recordMapper;

    /**
     * 1、添加课程到用户课表
     *
     * @param userId    用户ID
     * @param courseIds 课程ID集合
     */
    @Override
    @Transactional
    public void addLessons(Long userId, List<Long> courseIds) {
        // 1、根据课程ID集合 远程调用 查询课程信息（课程有效期）
        List<CourseSimpleInfoDTO> courseInfoList = courseClient.getSimpleInfoList(courseIds);
        if (ObjectUtil.isEmpty(courseInfoList) || courseInfoList.size() != courseIds.size()) {
            log.error("课程信息不存在，无法将课程加入到课表中");
            return;
        }

        // 2、遍历课程集合，组装课表数据
        List<LearningLesson> lessons = new ArrayList<>(courseInfoList.size());
        for (CourseSimpleInfoDTO courseInfo : courseInfoList) {
            LearningLesson lesson = new LearningLesson();
            // 2.1、填充userId、coueseId
            lesson.setUserId(userId);
            lesson.setCourseId(courseInfo.getId());

            // 2.2、填充课程过期时间
            Integer validDuration = courseInfo.getValidDuration();
            if (ObjectUtil.isEmpty(validDuration) || validDuration <= 0) {
                continue;
            }
            lesson.setExpireTime(LocalDateTime.now().plusMonths(validDuration));
            lessons.add(lesson);
        }

        // 3、批量新增
        this.saveBatch(lessons);
        log.info("用户：{}的课程：{} 加入到课表成功", userId, courseIds);
    }

    /**
     * 2、分页查询我的课表
     *
     * @param pageQuery
     * @return
     */
    @Override
    public PageDTO<LearningLessonVO> pageQueryMyLessons(PageQuery pageQuery) {
        // select * from `learning_lesson` where user_id = 2 order by latest_learn_time desc limit 0,5
        // 1、获取当前登录人
        Long userId = UserContext.getUser();

        // 2、发起分页查询
        /*Page<LearningLesson> page = Page.of(pageQuery.getPageNo(), pageQuery.getPageSize());
        if (ObjectUtil.isEmpty(pageQuery.getSortBy())) {
            page.addOrder(OrderItem.desc("latest_learn_time"));
        }else{
            page.addOrder(new OrderItem(pageQuery.getSortBy(),pageQuery.getIsAsc()));
        }*/

        Page<LearningLesson> pageResult = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .page(pageQuery.toMpPage("latest_learn_time", false));
        List<LearningLesson> records = pageResult.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return PageDTO.empty(pageResult);
        }

        // 3、发起远程调用，查询课程信息信息（课程名称、封面、总课时数）
        Map<Long, CourseSimpleInfoDTO> courseInfoList = queryCourseInfoAnd2Map(records);

        // 4、循环分页结果，将po list 转为 vo list
        List<LearningLessonVO> voList = new ArrayList<>(records.size());
        for (LearningLesson lesson : records) {
            // 4.1、拷贝 po 至 vo
            LearningLessonVO vo = BeanUtils.copyBean(lesson, LearningLessonVO.class);

            // 4.2、获取课程特有信息（课程名称、封面、总课时数），填充至vo
            CourseSimpleInfoDTO course = courseInfoList.get(lesson.getCourseId());

            vo.setCourseName(course.getName());
            vo.setCourseCoverUrl(course.getCoverUrl());
            vo.setSections(course.getSectionNum());

            //4.3、存入vo集合
            voList.add(vo);
        }

        // 5、封装最终的 PageDTO 并返回
        return PageDTO.of(pageResult, voList);
    }

    /**
     * 收集课程ID，远程调用查询课程信息并转为Map
     *
     * @param records
     * @return
     */
    private Map<Long, CourseSimpleInfoDTO> queryCourseInfoAnd2Map(List<LearningLesson> records) {
        // 3.1、收集当前页面的所有课程ID集合
        //Set<Long> courseIds = records.stream().map(LearningLesson::getCourseId).collect(Collectors.toSet());
        Set<Long> courseIds = CollStreamUtil.toSet(records, LearningLesson::getCourseId);

        // 3.2、发起远程调用
        List<CourseSimpleInfoDTO> courseInfoList = courseClient.getSimpleInfoList(courseIds);

        // 3.3、健壮性判断
        if (ObjectUtil.isEmpty(courseInfoList)) {
            throw new BizIllegalException("课程信息不存在，无法查询我的课表");
        }

        // 3.4、将list转换为Map，供后续高效使用
        /*Map<Long, CourseSimpleInfoDTO> couseInfoMap = courseInfoList.stream()
                .collect(Collectors.toMap(CourseSimpleInfoDTO::getId, Function.identity()));*/

        Map<Long, CourseSimpleInfoDTO> couseInfoMap = CollStreamUtil.toIdentityMap(courseInfoList, CourseSimpleInfoDTO::getId);
        return couseInfoMap;
    }

    /**
     * 3、查询我正在学习的课程（Day2 - 作业1）
     *
     * @return
     */
    @Override
    public LearningLessonVO queryMyCurrentLesson() {
        // 1.获取当前登录的用户
        Long userId = UserContext.getUser();
        // 2.查询正在学习的课程 select * from xx where user_id = #{userId} AND status = 1 order by latest_learn_time desc limit 1
        LearningLesson lesson = lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getStatus, LEARNING.getValue())
                .orderByDesc(LearningLesson::getLatestLearnTime)
                .last("limit 1")
                .one();
        if (lesson == null) {
            return null;
        }
        // 3.拷贝PO基础属性到VO
        LearningLessonVO vo = BeanUtils.copyBean(lesson, LearningLessonVO.class);
        // 4.查询课程信息
        CourseFullInfoDTO cInfo = courseClient.getCourseInfoById(lesson.getCourseId(), false, false);
        if (cInfo == null) {
            throw new BadRequestException("课程不存在");
        }
        vo.setCourseName(cInfo.getName());
        vo.setCourseCoverUrl(cInfo.getCoverUrl());
        vo.setSections(cInfo.getSectionNum());
        // 5.统计课表中的课程数量 select count(1) from xxx where user_id = #{userId}
        Integer courseAmount = lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .count();
        vo.setCourseAmount(courseAmount);
        // 6.查询小节信息
        List<CataSimpleInfoDTO> cataInfos =
                catalogueClient.batchQueryCatalogue(CollUtils.singletonList(lesson.getLatestSectionId()));
        if (!CollUtils.isEmpty(cataInfos)) {
            CataSimpleInfoDTO cataInfo = cataInfos.get(0);
            vo.setLatestSectionName(cataInfo.getName());
            vo.setLatestSectionIndex(cataInfo.getCIndex());
        }
        return vo;
    }

    /**
     * 4、查询指定课程信息（Day2 - 作业2）
     *
     * @param courseId
     * @return
     */
    @Override
    public LearningLessonVO queryLessonByCourseId(Long courseId) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.查询课程信息 select * from xx where user_id = #{userId} AND course_id = #{courseId}
        LearningLesson lesson = getOne(buildUserIdAndCourseIdWrapper(userId, courseId));
        if (lesson == null) {
            return null;
        }
        // 3.处理VO
        return BeanUtils.copyBean(lesson, LearningLessonVO.class);
    }

    /**
     * 5、删除指定课程信息（Day2 - 作业3）
     *
     * @param userId
     * @param courseId
     */
    @Override
    public void deleteCourseFromLesson(Long userId, List<Long> courseId) {
        // 1.获取当前登录用户
        if (userId == null) {
            userId = UserContext.getUser();
        }
        // 2.删除课程
        LambdaQueryWrapper<LearningLesson> queryWrapper = new QueryWrapper<LearningLesson>()
                .lambda()
                .eq(LearningLesson::getUserId, userId)
                .in(LearningLesson::getCourseId, courseId);

        remove(queryWrapper);
    }

    /**
     * 6、统计课程学习人数（Day2 - 作业4）
     *
     * @param courseId
     * @return
     */
    @Override
    public Integer countLearningLessonByCourse(Long courseId) {
        // select count(1) from xx where course_id = #{cc} AND status in (0, 1, 2)
        return lambdaQuery()
                .eq(LearningLesson::getCourseId, courseId)
                .in(LearningLesson::getStatus,
                        NOT_BEGIN.getValue(),
                        LEARNING.getValue(),
                        LessonStatus.FINISHED.getValue())
                .count();
    }

    /**
     * 7、校验当前课程是否已经报名（Day2 - 作业5）
     *
     * @param courseId
     * @return
     */
    @Override
    public Long isLessonValid(Long courseId) {
        // 1.获取登录用户
        Long userId = UserContext.getUser();
        if (userId == null) {
            return null;
        }
        // 2.查询课程
        LearningLesson lesson = getOne(buildUserIdAndCourseIdWrapper(userId, courseId));
        if (lesson == null || LessonStatus.EXPIRED.equals(lesson.getStatus())) {
            return null;
        }
        return lesson.getId();
    }

    /**
     * 8、创建学习计划
     *
     * @param planDTO
     */
    @Override
    public void createPlans(LearningPlanDTO planDTO) {
        LearningLesson lesson = getOne(buildUserIdAndCourseIdWrapper(UserContext.getUser(), planDTO.getCourseId()));
        AssertUtils.isNotNull(lesson, "课表不存在，无法创建学习计划");

        this.lambdaUpdate()
                .set(LearningLesson::getWeekFreq, planDTO.getFreq())
                .set(lesson.getPlanStatus() == PlanStatus.NO_PLAN, LearningLesson::getPlanStatus, PlanStatus.PLAN_RUNNING)
                .eq(LearningLesson::getId, lesson.getId())
                .update();
    }

    /**
     * 9、查询我的学习计划
     *
     * @param pageQuery
     * @return
     */
    @Override
    public LearningPlanPageVO queryMyPlans(PageQuery pageQuery) {
        LearningPlanPageVO vo = new LearningPlanPageVO();

        // 1、分页查询 我的课表（本周计划学习小节数、已学完小节数、最近学习时间、课程ID） - 我的、制定过学习计划的、课表状态是 未学习和学习中的
        // select * from learning_lesson where user_id = 2 and plan_status = 1 and status in (0, 1) order by latest_learn_time desc limit 0,10
        Page<LearningLesson> pageResult = this.lambdaQuery()
                .eq(LearningLesson::getUserId, UserContext.getUser())
                .eq(LearningLesson::getPlanStatus, PlanStatus.PLAN_RUNNING)
                .in(LearningLesson::getStatus, NOT_BEGIN, LEARNING)
                .page(pageQuery.toMpPage("latest_learn_time", false));
        List<LearningLesson> records = pageResult.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return vo.emptyPage(pageResult);
        }

        // 2、收集课程ID集合，远程调用查询课程信息（Map -> 课程ID：课程对象）
        Map<Long, CourseSimpleInfoDTO> courseInfoMap = queryCourseInfoAnd2Map(records);

        // 3、统计本周实际学习小节数 （Map -> 课表ID：实际学习小节数）
        // SELECT lesson_id,COUNT(1) num FROM learning_record WHERE user_id = 2 AND finished = 1
        // AND finish_time BETWEEN '2025-10-20' AND '2025-10-26' GROUP BY lesson_id
        // 3.1、获取本周开始、结束日期
        LocalDateTime begin = DateUtils.getWeekBeginTime(LocalDate.now());
        LocalDateTime end = DateUtils.getWeekEndTime(LocalDate.now());

        // 3.2、发起分组统计
        QueryWrapper<LearningRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("lesson_id,COUNT(1) num")
                .eq("user_id", UserContext.getUser())
                .eq("finished", true)
                .between("finish_time", begin, end)
                .groupBy("lesson_id");

        List<Map<String, Object>> mapList = this.recordMapper.selectMaps(queryWrapper);
        // mapList
        // Map1
        // "lesson_id"  1979461706306191362
        // "num"  4
        // Map1
        // "lesson_id"  1979488146921787393
        // "num"  9

        // Map
        //  "1979461706306191362"   4
        //  "1979488146921787393"  9
        Map<Long, Long> learnedSectionNumMap = mapList.stream().collect(Collectors.toMap(
                m -> (Long) m.get("lesson_id"),
                m -> (Long) m.get("num")
        ));

        List<LearningRecord> objectList = this.recordMapper.selectList(queryWrapper);
        Map<Long, Long> learnedSectionNumMap2 = objectList.stream().collect(Collectors.toMap(
                LearningRecord::getLessonId, LearningRecord::getNum)
        );


        // 4、循环分页课表数据，填充缺失数据
        List<LearningPlanVO> voList = new ArrayList<>(records.size());
        for (LearningLesson lesson : records) {
            // 4.1、拷贝 po 数据至 vo
            LearningPlanVO learningPlanVO = BeanUtils.toBean(lesson, LearningPlanVO.class);

            // 4.2、填充课程数据
            CourseSimpleInfoDTO courseInfo = courseInfoMap.get(lesson.getCourseId());
            if (ObjectUtil.isNotNull(courseInfo)) {
                learningPlanVO.setCourseName(courseInfo.getName());
                learningPlanVO.setSections(courseInfo.getSectionNum());
            }

            // 4.3、填充本周已学习小节数
            learningPlanVO.setWeekLearnedSections(learnedSectionNumMap.getOrDefault(lesson.getId(), 0L).intValue());

            // 4.4、添加至集合
            voList.add(learningPlanVO);
        }

        // 5、计算本周已学习小节总数量  TODO
        long sum = learnedSectionNumMap.values().stream().mapToLong(num -> num.longValue()).sum();
        long sum2 = learnedSectionNumMap.values().stream().mapToLong(Long::longValue).sum();

        long sum3 = learnedSectionNumMap.values().stream().flatMapToLong(num -> LongStream.of(num)).sum();
        long sum4 = learnedSectionNumMap.values().stream().map(Function.identity()).reduce(Long::sum).get();
        long sum5 = learnedSectionNumMap.values().stream().collect(Collectors.summingLong(num -> num));
        long sum6 = learnedSectionNumMap.values().stream().mapToLong(num -> num).summaryStatistics().getSum();

        // 6、计算本周计划学习小节总数量 TODO
        // select sum(week_freq) as total_weekfreq from learning_lesson where user_id = 2 and plan_status = 1 and status in (0, 1)
        LearningLesson lesson = this.query()
                .select("sum(week_freq) as total_weekfreq")
                .eq("user_id", UserContext.getUser())
                .eq("plan_status", PlanStatus.PLAN_RUNNING)
                .in("status", NOT_BEGIN, LEARNING)
                .one();

        // 7、封装数据并返回
        vo.setWeekFinished(Long.valueOf(sum).intValue());
        vo.setWeekTotalPlan(lesson.getTotalWeekfreq());
        vo.pageInfo(pageResult.getTotal(), pageResult.getPages(), voList);
        return vo;
    }


    private LambdaQueryWrapper<LearningLesson> buildUserIdAndCourseIdWrapper(Long userId, Long courseId) {
        LambdaQueryWrapper<LearningLesson> queryWrapper = new QueryWrapper<LearningLesson>()
                .lambda()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getCourseId, courseId);
        return queryWrapper;
    }


}
